﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Cyberarms.Agents.MailServer.Test {
    [TestClass]
    public class Pop3Test {
        [TestMethod]
        public void TestPop3Parser() {
            byte[] testDataPass = new byte[] { 0x45, 0x00, 0x00, 0x3B, 0x23, 0x44, 0x40, 0x00, 0x7A, 0x06, 0x5A, 0xF6, 0x57, 0x98, 0x4A, 0x1E, 0x51, 0xA9, 0x8F, 0x23, 0xC8, 0xDC, 0x00, 0x6E, 0x91, 0x49, 0x3A, 0x6C, 0x8C, 0x47, 0xB3, 0xFB, 0x50, 0x18, 0x01, 0x04, 0x42, 0xD8, 0x00, 0x00, 0x50, 0x41, 0x53, 0x53, 0x20, 0x69, 0x73, 0x69, 0x43, 0x6F, 0x72, 0x65, 0x41, 0x64, 0x6D, 0x69, 0x6E, 0x0D, 0x0A };
            Pop3Agent agent = new Pop3Agent();
            agent.TestReceive(testDataPass);
            foreach (int key in agent.CurrentClients.Keys) {
                Assert.AreEqual(Pop3Message.PASS, agent.CurrentClients[key].LastMessage);
            }
        }

        [TestMethod]
        public void TestPop3ErrMsg() {
            byte[] testErrMsg = new byte[] { 0x45, 0x00, 0x00, 0x3F, 0x62, 0xDC, 0x40, 0x00, 0x80, 0x06, 0x15, 0x5A, 0x51, 0xA9, 0x8F, 0x23, 0x57, 0x98, 0x4A, 0x1E, 0x00, 0x6E, 0xC8, 0xDC, 0x8C, 0x47, 0xB3, 0xFB, 0x91, 0x49, 0x3A, 0x7F, 0x50, 0x18, 0x01, 0x04, 0xE4, 0x3D, 0x00, 0x00, 0x2D, 0x45, 0x52, 0x52, 0x20, 0x55, 0x6E, 0x61, 0x62, 0x6C, 0x65, 0x20, 0x74, 0x6F, 0x20, 0x6C, 0x6F, 0x67, 0x20, 0x6F, 0x6E, 0x0D, 0x0A };
            byte[] testDataPass = new byte[] { 0x45, 0x00, 0x00, 0x3B, 0x23, 0x44, 0x40, 0x00, 0x7A, 0x06, 0x5A, 0xF6, 0x57, 0x98, 0x4A, 0x1E, 0x51, 0xA9, 0x8F, 0x23, 0xC8, 0xDC, 0x00, 0x6E, 0x91, 0x49, 0x3A, 0x6C, 0x8C, 0x47, 0xB3, 0xFB, 0x50, 0x18, 0x01, 0x04, 0x42, 0xD8, 0x00, 0x00, 0x50, 0x41, 0x53, 0x53, 0x20, 0x69, 0x73, 0x69, 0x43, 0x6F, 0x72, 0x65, 0x41, 0x64, 0x6D, 0x69, 0x6E, 0x0D, 0x0A };
            
            Pop3Agent agent = new Pop3Agent();
            agent.TestReceive(testDataPass);
            attackDetected = false;
            agent.AttackDetected += new IntrusionDetection.Api.Plugin.AttackDetectedHandler(agent_AttackDetected);
            agent.TestSend(testErrMsg);
            System.Threading.Thread.Sleep(100);
            Assert.IsTrue(attackDetected);
        }

        bool attackDetected = false;

        void agent_AttackDetected(object sender, IntrusionDetection.Api.Plugin.INotificationEventArgs data) {
            attackDetected = true;
            System.Diagnostics.Debug.Print(data.EventMessage);
        }

        [TestMethod]
        public void TestPop3Watcher() {
            Pop3Agent agent = new Pop3Agent();
            agent.AttackDetected+=new IntrusionDetection.Api.Plugin.AttackDetectedHandler(agent_AttackDetected);
            agent.Start();
            System.Threading.Thread.Sleep(600000);
            Assert.Fail("This test is long running, and takes manual steps");
        }
    }
}
